package com.quectel.core.module.partybuildingsurvey.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.quectel.constant.core.partybuilding.PartySurveyConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.partybuildingsurvey.dao.PartySurveyQuestionDao;
import com.quectel.core.module.partybuildingsurvey.dto.PartySurveyAnswerDto;
import com.quectel.core.module.partybuildingsurvey.dto.PartySurveyPersonAnswerDto;
import com.quectel.core.module.partybuildingsurvey.dto.PartySurveyQuestionDto;
import com.quectel.core.module.partybuildingsurvey.dto.count.PartySurveyPersonRecordEvaluateCount;
import com.quectel.core.module.partybuildingsurvey.entity.PartySurveyQuestionEntity;
import com.quectel.core.module.partybuildingsurvey.service.PartySurveyAnswerService;
import com.quectel.core.module.partybuildingsurvey.service.PartySurveyPersonAnswerService;
import com.quectel.core.module.partybuildingsurvey.service.PartySurveyQuestionService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.common.JacksonUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author bob
 * @email bob.yu@quectel.com
 * @date 2023/05/24 11:38
 */
@DubboService
public class PartySurveyQuestionServiceImpl implements PartySurveyQuestionService {

    private static final Logger LOGGER = LoggerFactory.getLogger(PartySurveyQuestionServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> PARTY_SURVEY_QUESTION_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "PARTY_SURVEY_QUESTION_CACHE_BY_ID:%d", id);
    private static final Function<Long, String> PARTY_SURVEY_QUESTION_CACHE_BY_ID_NO_PADDING_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "PARTY_SURVEY_QUESTION_CACHE_BY_ID_NO_PADDING_FUNC:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<PartySurveyQuestionDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(PARTY_SURVEY_QUESTION_CACHE_BY_ID_FUNC.apply(dto.getId()));
        CacheKit.invalidRedisCache(PARTY_SURVEY_QUESTION_CACHE_BY_ID_NO_PADDING_FUNC.apply(dto.getId()));
    };

    @Autowired
    private PartySurveyQuestionDao partySurveyQuestionDao;
    @Autowired
    private PartySurveyAnswerService partySurveyAnswerService;
    @Autowired
    private PartySurveyPersonAnswerService partySurveyPersonAnswerService;

    @Override
    public PartySurveyQuestionDto questionCount(PartySurveyQuestionDto partySurveyQuestionDto) {
        //查询对应题目的回答
        List<PartySurveyPersonAnswerDto> answerDtos = partySurveyPersonAnswerService.selectBySurveyIdAndQuestionId(partySurveyQuestionDto.getPartySurveyId(), partySurveyQuestionDto.getId());

        if (CollectionUtils.isEmpty(answerDtos)) {
            partySurveyQuestionDto.setAnswerCount(0L);
            if (PartySurveyConstants.QuestionType.EVALUATE.getType().equals(partySurveyQuestionDto.getType())){
                PartySurveyAnswerDto partySurveyAnswerDto = partySurveyQuestionDto.getBindAnswer().get(0);
                partySurveyAnswerDto.handleDefaultEvaluateCount();
            }
            return partySurveyQuestionDto;
        }

        if (PartySurveyConstants.QuestionType.SINGLE_CHOICE.getType().equals(partySurveyQuestionDto.getType())
                || PartySurveyConstants.QuestionType.MULTIPLE_CHOICE.getType().equals(partySurveyQuestionDto.getType())
                || PartySurveyConstants.QuestionType.PIC_SINGLE_CHOICE.getType().equals(partySurveyQuestionDto.getType())
                || PartySurveyConstants.QuestionType.PIC_MULTIPLE_CHOICE.getType().equals(partySurveyQuestionDto.getType())
        ) {
            return choiceCount(partySurveyQuestionDto, answerDtos);
        } else if (PartySurveyConstants.QuestionType.EVALUATE.getType().equals(partySurveyQuestionDto.getType())) {
            return evaluateCount(partySurveyQuestionDto, answerDtos);
        } else {
            partySurveyQuestionDto.setAnswerCount((long) answerDtos.size());
            return partySurveyQuestionDto;
        }
    }

    private PartySurveyQuestionDto choiceCount(PartySurveyQuestionDto question, List<PartySurveyPersonAnswerDto> answerDtos) {
        //选项
        List<PartySurveyAnswerDto> bindAnswer = question.getBindAnswer();
        for (PartySurveyAnswerDto partySurveyAnswerDto : bindAnswer) {
            //统计每个答案出现的次数
            long count = answerDtos.stream().filter(partySurveyPersonAnswerDto -> partySurveyPersonAnswerDto.getContent().contains(String.valueOf(partySurveyAnswerDto.getId()))).count();
            partySurveyAnswerDto.setAnswerCount(count);
        }

        List<PartySurveyAnswerDto> collect = question.getBindAnswer().stream().sorted(Comparator.comparing(PartySurveyAnswerDto::getAnswerCount).reversed()).collect(Collectors.toList());
        Integer rank = 1;
        for (int i = 0; i < collect.size(); i++) {
            //如果和前一个一样 则不递增
            if(i > 0 && !collect.get(i-1).getAnswerCount().equals(collect.get(i).getAnswerCount())){
                rank++;
            }
            collect.get(i).setRank(rank);
        }
        question.setBindAnswer(collect);
        question.setAnswerCount((long) answerDtos.size());
        return question;
    }

    private PartySurveyQuestionDto evaluateCount(PartySurveyQuestionDto question, List<PartySurveyPersonAnswerDto> answerDtos) {
        //提取出来所有的分数 然后计算平均分 最大分和最小分
        //选项
        List<PartySurveyAnswerDto> bindAnswer = question.getBindAnswer();
        for (PartySurveyAnswerDto partySurveyAnswerDto : bindAnswer) {
            List<Double> scores = new ArrayList<>();
            //统计每个答案出现的次数
            answerDtos.forEach(partySurveyPersonAnswerDto -> {
                Map<String, Double> parse = JacksonUtils.parse(partySurveyPersonAnswerDto.getContent(), new TypeReference<HashMap<String, Double>>() {
                });
                Double score = parse.get(String.valueOf(partySurveyAnswerDto.getId()));
                if(score!=null){
                    scores.add(score);
                }
            });
            partySurveyAnswerDto.setAnswerCount((long) scores.size());
            // 平均值
            double average = scores.stream().mapToDouble(Double::doubleValue).average().orElse(0d);
            // 最大值
            Double max = scores.stream().mapToDouble(Double::doubleValue).max().orElse(0d);
            // 最小值
            Double min = scores.stream().mapToDouble(Double::doubleValue).min().orElse(0d);

            Map<Double, Long> counted = scores.stream()
                    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
            PartySurveyPersonRecordEvaluateCount evaluateCount = new PartySurveyPersonRecordEvaluateCount();
            List<PartySurveyPersonRecordEvaluateCount.EvaluateCount> evaluateCounts = new ArrayList<>();
            counted.forEach((aDouble, aLong) -> {
                PartySurveyPersonRecordEvaluateCount.EvaluateCount count = new PartySurveyPersonRecordEvaluateCount.EvaluateCount();
                count.setScore(aDouble);
                count.setCount(aLong);
                evaluateCounts.add(count);
            });
            PartySurveyPersonRecordEvaluateCount.EvaluateStatistics evaluateStatistics = new PartySurveyPersonRecordEvaluateCount.EvaluateStatistics();
            evaluateStatistics.setMinScore(min);
            evaluateStatistics.setMaxScore(max);
            evaluateStatistics.setAvgScore(average);

            evaluateCount.setEvaluateCounts(evaluateCounts.stream().sorted(Comparator.comparing(PartySurveyPersonRecordEvaluateCount.EvaluateCount::getScore)).collect(Collectors.toList()));
            evaluateCount.setEvaluateStatistics(evaluateStatistics);

            partySurveyAnswerDto.setEvaluateCount(evaluateCount);
        }
        question.setAnswerCount((long) answerDtos.size());
        return question;

    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Long saveOrUpdate(PartySurveyQuestionDto partySurveyQuestionDto) {
        if (partySurveyQuestionDto.getId() == null) {
            Long id = save(partySurveyQuestionDto);
            partySurveyQuestionDto.setId(id);
        } else {
            updateById(partySurveyQuestionDto);
        }

        partySurveyAnswerService.deleteBySurveyIdAndQuestionId(partySurveyQuestionDto.getPartySurveyId(), partySurveyQuestionDto.getId());

        if (CollectionUtils.isNotEmpty(partySurveyQuestionDto.getBindAnswer())) {
            // 绑定下党员信息到中间表
            for (PartySurveyAnswerDto bindingDto : partySurveyQuestionDto.getBindAnswer()) {
                bindingDto.setPartySurveyId(partySurveyQuestionDto.getPartySurveyId());
                bindingDto.setQuestionId(partySurveyQuestionDto.getId());

                if (PartySurveyConstants.QuestionType.BLANK.getType().equals(partySurveyQuestionDto.getType())) {
                    bindingDto.setCustomAttr(JacksonUtils.toJsonString(bindingDto.getBlankData()));
                }

                if (PartySurveyConstants.QuestionType.PIC_SINGLE_CHOICE.getType().equals(partySurveyQuestionDto.getType()) || PartySurveyConstants.QuestionType.PIC_MULTIPLE_CHOICE.getType().equals(partySurveyQuestionDto.getType())) {
                    bindingDto.setCustomAttr(JacksonUtils.toJsonString(bindingDto.getImageData()));
                }
                if (PartySurveyConstants.QuestionType.EVALUATE.getType().equals(partySurveyQuestionDto.getType())) {
                    bindingDto.setCustomAttr(JacksonUtils.toJsonString(bindingDto.getLabelDataList()));
                }

                bindingDto.setCreateTime(new Date());
                partySurveyAnswerService.save(bindingDto);
            }
        }

        return partySurveyQuestionDto.getId();
    }


    @Override
    public List<PartySurveyQuestionDto> selectBySurveyId(Long surveyId) {
        List<PartySurveyQuestionEntity> list = partySurveyQuestionDao.selectList(new LambdaQueryWrapper<PartySurveyQuestionEntity>().eq(PartySurveyQuestionEntity::getPartySurveyId, surveyId));
        List<PartySurveyQuestionDto> result = CopyUtils.copyList(list, PartySurveyQuestionDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    @Override
    public void deleteBySurveyId(Long surveyId) {
        partySurveyQuestionDao.delete(new LambdaQueryWrapper<PartySurveyQuestionEntity>()
                .eq(PartySurveyQuestionEntity::getPartySurveyId, surveyId));
    }


    @Override
    public PartySurveyQuestionDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                PARTY_SURVEY_QUESTION_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public PartySurveyQuestionDto selectCacheByIdNoPadding(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectByIdNoPadding(id),
                PARTY_SURVEY_QUESTION_CACHE_BY_ID_NO_PADDING_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public PartySurveyQuestionDto selectByIdNoPadding(Long id) {
        PartySurveyQuestionEntity entity = partySurveyQuestionDao.selectById(id);
        return CopyUtils.copyObj(entity, PartySurveyQuestionDto.class);
    }

    @Override
    public PartySurveyQuestionDto selectById(Long id) {
        PartySurveyQuestionEntity entity = partySurveyQuestionDao.selectById(id);
        PartySurveyQuestionDto partySurveyQuestionDto = paddingField(CopyUtils.copyObj(entity, PartySurveyQuestionDto.class));

        if (partySurveyQuestionDto != null) {
            List<PartySurveyAnswerDto> partySurveyAnswerDtos = partySurveyAnswerService.selectBySurveyIdAndQuestionId(partySurveyQuestionDto.getPartySurveyId(), partySurveyQuestionDto.getId());
            partySurveyQuestionDto.setBindAnswer(partySurveyAnswerDtos.stream().sorted(Comparator.comparing(PartySurveyAnswerDto::getSort)).collect(Collectors.toList()));
        }

        return partySurveyQuestionDto;
    }

    @Override
    public List<PartySurveyQuestionDto> queryList(Map<String, Object> params) {
        List<PartySurveyQuestionEntity> list = partySurveyQuestionDao.queryList(params);
        List<PartySurveyQuestionDto> result = CopyUtils.copyList(list, PartySurveyQuestionDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private PartySurveyQuestionDto paddingField(PartySurveyQuestionDto dto) {
        if (dto != null) {
            List<PartySurveyAnswerDto> partySurveyAnswerDtos = partySurveyAnswerService.selectBySurveyIdAndQuestionId(dto.getPartySurveyId(), dto.getId());

            partySurveyAnswerDtos.forEach(partySurveyAnswerDto -> {
                if (PartySurveyConstants.QuestionType.PIC_SINGLE_CHOICE.getType().equals(dto.getType()) || PartySurveyConstants.QuestionType.PIC_MULTIPLE_CHOICE.getType().equals(dto.getType())) {
                    partySurveyAnswerDto.setImageData(JacksonUtils.parse(partySurveyAnswerDto.getCustomAttr(), PartySurveyAnswerDto.ImageData.class));
                }
                if (PartySurveyConstants.QuestionType.BLANK.getType().equals(dto.getType())) {
                    partySurveyAnswerDto.setBlankData(JacksonUtils.parse(partySurveyAnswerDto.getCustomAttr(), PartySurveyAnswerDto.BlankData.class));
                }
                if (PartySurveyConstants.QuestionType.EVALUATE.getType().equals(dto.getType())) {
                    partySurveyAnswerDto.setLabelDataList(JacksonUtils.parseArray(partySurveyAnswerDto.getCustomAttr(), PartySurveyAnswerDto.LabelData.class));
                }
            });
            dto.setBindAnswer(partySurveyAnswerDtos);

            if (PartySurveyConstants.QuestionType.MULTIPLE_CHOICE.getType().equals(dto.getType()) || PartySurveyConstants.QuestionType.PIC_MULTIPLE_CHOICE.getType().equals(dto.getType())) {
                dto.setMultipleConfig(JacksonUtils.parse(dto.getCustomAttr(), PartySurveyQuestionDto.MultipleConfig.class));
            }
        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return partySurveyQuestionDao.queryTotal(params);
    }

    @Override
    public Long save(PartySurveyQuestionDto dto) {
        PartySurveyQuestionEntity entity = CopyUtils.copyObj(dto, PartySurveyQuestionEntity.class);
        entity.setId(Snowflake.nextId());
        partySurveyQuestionDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(PartySurveyQuestionDto dto) {
        PartySurveyQuestionEntity entity = CopyUtils.copyObj(dto, PartySurveyQuestionEntity.class);

        partySurveyQuestionDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(PartySurveyQuestionDto dto) {
        PartySurveyQuestionEntity entity = CopyUtils.copyObj(dto, PartySurveyQuestionEntity.class);

        MyBatisPlusUtils.updateAllColumnById(entity, partySurveyQuestionDao);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id) {

        CLEAR_CACHE_FUNC.accept(selectById(id));

        partySurveyQuestionDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
